#!/bin/sh
# Altera Qsys and Quartus generation script.

QUARTUS_PRJ_PATH=$1

SKIP_BITS=
while [ $# -gt 0 ]
do
    case "$1" in
        --skip-bits)
        echo "INFO: Skipping Quartus compilation"
        SKIP_BITS=1
        ;;
        --help)
        echo "Usage: $0 <QUARTUS_PRJ_PATH> [OPTION]"
        echo
        echo "OPTION:"
        echo "  --skip-bits     Skip Quartus compilation (only Qsys generation)"
        echo
        exit 1
        ;;
    esac
    shift
done

echo
echo "INFO: Starting qsys-generate in path ${QUARTUS_PRJ_PATH}"
qsys-generate ${QUARTUS_PRJ_PATH}/*.qsys --synthesis=VERILOG

#check return
if [ $? -ne 0 ]; then
    echo
    echo "ERROR: qsys-generate in path ${QUARTUS_PRJ_PATH} failed"
    exit 1
fi

# Do Quartus flow if skip variable is empty
if [ -z "${SKIP_BITS}" ];
then
    #Workaround: Remove done file
    if [ -f ${QUARTUS_PRJ_PATH}/*.done ]
    then
        rm ${QUARTUS_PRJ_PATH}/*.done
    fi

    echo
    echo "INFO: Starting Quartus compilation in path ${QUARTUS_PRJ_PATH}"
    quartus_cmd ${QUARTUS_PRJ_PATH}/*.qpf -c ${QUARTUS_PRJ_PATH}/*.qsf

    #Workaround: Quartus returned unsuccessful if done file doesn't exist
    if [ ! -f ${QUARTUS_PRJ_PATH}/*.done ]
    then
        echo
        echo "ERROR: Quartus compilation in path ${QUARTUS_PRJ_PATH} failed"
        exit 1
    fi
fi

exit 0
